package ssd8.socket.http;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * MultiHTTPServer
 *
 * @author 龙虹宇
 * @version 1.0
 * @date 2023/10/16
 */


public class MultiHTTPServer {
    private static ExecutorService executorService;  //线程池
    private static final int POOL_SIZE = 4; //单个处理器线程池工作线程数目

    public static void main(String[] args) throws IOException {
        int port = 80;
        // args = new String[]{"" + System.getProperty("user.dir")};

        // 判断是否携带启动参数
        if (args.length != 1) {
            System.out.println("未设置根目录！");
            System.exit(0);
        }

        String rootDirectory = args[0]; // 服务器的根目录

        // 创建服务器套接字并开始监听
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("HTTP Server is running on port " + port);

        //创建线程池
        //Runtime的availableProcessors()方法返回当前系统可用处理器的数目
        //由JVM根据系统的情况来决定线程的数量
        executorService=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_SIZE);

        while (true) {
            try {
                Socket socket = serverSocket.accept(); //等待用户连接
                executorService.execute(new ServerHandler(socket, rootDirectory)); //把执行交给线程池来维护
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}